<template>
  <div>
    <!-- 标题栏 -->
    <NavBar :title="title" :rightBtn="rightBtn" @handleIcon="hanldleRight">
    </NavBar>
    <chat-box
      @submit="sendText"
      @onrefresh="onrefresh"
      :messages="messages"
      :outloading="loading"
    ></chat-box>
  </div>
</template>

<script>
import moment from "moment";
import { mapGetters } from "vuex";
import ChatBox from "@/components/Chat/ChatBox";
import NavBar from "@/components/NavBar";
import {
  D_UserMessage_GetUserList,
  D_UserMessage_GetPageHistoryDataList,
  D_UserMessage_GetHistoryDataList
} from "@/api/D_Manage/D_UserMessage";

const uuid = require("uuid");

var messageType = 2;
var readmessageType = 6;
var uid = uuid.v4();

export default {
  components: {
    ChatBox,
    NavBar
  },
  mounted() {
    this.socketApi.addcallback(this.getConfigResult, messageType);
    this.rightBtn.number++;
    this.rightBtn.iconName.unshift("ellipsis");

    this.getDataList();

    if (this.$route.params.user) {
      var user = JSON.parse(this.$route.params.user);
      if (user) {
        this.nagative(
          user.UserId,
          user.UserName,
          user.Avatar,
          user.IsGroup,
          user.UserIds,
          user.UserNames
        );
      }
    }

    if (this.$route.params.message) {
      var message = JSON.parse(this.$route.params.message);

      if (message) {
        this.openForm(
          message.CreatorId,
          message.CreatorName,
          message.Avatar,
          message.GroupId,
          message.GroupName,
          message.UserIds,
          message.UserNames
        );
      }
    }
  },
  data() {
    return {
      rightBtn: {
        number: 0,
        iconName: []
      },
      loading: false,
      messages: [],
      contentText: null,
      selectedUserId: null,
      selectedUserName: null,
      selectedUserAvatar: null,
      groupId: null,
      selectedUserIds: null,
      selectedUserNames: null,
      title: "",
      userdatas: [],
      localdatas: JSON.parse(localStorage.getItem("userdatas")) || []
    };
  },
  methods: {
    nagative(id, name, avatar, isGroup, userids, usernames) {
      if (isGroup) {
        this.openForm(id, name, avatar, id, name, userids, usernames);
      } else {
        this.openForm(id, name, avatar, null, null, userids, usernames);
      }
    },
    openForm(id, name, avatar, groupid, groupname, userids, usernames) {
      //参数赋值
      this.title = groupname || name;
      this.loading = true;
      //组件初始化
      this.init();
      this.selectedUserId = id;
      this.selectedUserName = name;
      this.selectedUserAvatar = avatar;
      this.groupId = groupid;
      this.selectedUserIds = userids;
      this.selectedUserNames = usernames;
      //编辑赋值
      this.getUnReadData();
    },
    init() {
      this.visible = true;
      this.messages = [];
      this.selectedUserId = null;
      this.selectedUserName = null;
      this.selectedUserAvatar = null;
      this.groupId = null;
      this.selectedUserIds = null;
      this.selectedUserNames = null;
    },
    hanldleRight(item) {},
    sendText(text, type) {
      if (!text || !this.selectedUserId) {
        return;
      }
      let sendMessage = {};
      sendMessage.Text = text.replace("\n", "");
      sendMessage.CreateTime = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
      sendMessage.CreatorName = this.userInfo.UserName;
      sendMessage.CreatorId = this.userInfo.Id;
      if (this.groupId) {
        sendMessage.GroupId = this.groupId;
        sendMessage.GroupName = this.groupname;
        sendMessage.UserNames = this.selectedUserNames;
        sendMessage.UserIds = this.selectedUserIds;
      } else {
        sendMessage.UserNames = "^" + this.selectedUserName + "^";
        sendMessage.UserIds = "^" + this.selectedUserId + "^";
      }
      sendMessage.Avatar = this.userInfo.Avatar;
      if (type) {
        sendMessage.Type = type;
      } else {
        sendMessage.Type = 1;
      }
      let send = {
        Success: true,
        Data: sendMessage,
        MessageType: messageType
      };
      this.socketApi.sendSock(JSON.stringify(send));
    },
    getConfigResult(res) {
      // 接收回调函数返回数据的方法
      let resmsg = res;
      if (!this.selectedUserId) {
        return;
      }
      if (
        (!this.groupId &&
          !resmsg.GroupId &&
          (resmsg.CreatorId === this.userInfo.Id ||
            resmsg.CreatorId === this.selectedUserId)) ||
        (this.groupId && this.groupId === resmsg.GroupId)
      ) {
        let endmsg = null;
        if (this.messages && this.messages.length > 0) {
          endmsg = this.messages[this.messages.length - 1];
        }
        if (endmsg !== null && typeof endmsg !== "undefined") {
          let date1 = new Date(resmsg.CreateTime); //开始时间
          let date2 = new Date(endmsg.CreateTime); //结束时间
          let date3 = date1.getTime() - date2.getTime(); //时间差的毫秒数
          if (date3 > 60000) {
            resmsg.ShowTime = true;
          } else {
            resmsg.ShowTime = false;
          }
        } else {
          resmsg.ShowTime = true;
        }
        this.messages = this.messages.concat(resmsg);

        if (resmsg.CreatorId != this.userInfo.Id) {
          if (
            (resmsg.ReadingMarks || "").indexOf(
              "^" + this.userInfo.Id + "^"
            ) === -1
          ) {
            resmsg.ReadingMarks =
              (resmsg.ReadingMarks || "^") + this.userInfo.Id + "^";
            resmsg.ModifyTime = moment(new Date()).format(
              "YYYY-MM-DD HH:mm:ss"
            );
            //设为已读
            let send = {
              Success: true,
              Data: resmsg,
              MessageType: readmessageType
            };
            this.socketApi.sendSock(JSON.stringify(send));
          }

          let tempdata = null;
          if (!resmsg.GroupId) {
            tempdata = this.userdatas.find(d => d.UserId === resmsg.CreatorId);
          } else {
            tempdata = this.userdatas.find(d => d.UserId === resmsg.GroupId);
          }
          if (tempdata) {
            tempdata.LastDateTime = resmsg.CreateTime;
            tempdata.LastMessage = resmsg.Text;
          }
        }
      }
    },
    onrefresh() {
      var endValue = new Date();
      if (this.messages && this.messages.length > 0) {
        endValue = this.messages[0].CreateTime;
      }
      this.getHisData(endValue);
    },
    getHisData(endValue) {
      if (!this.selectedUserId) {
        return;
      }
      if (endValue) {
        this.loading = true;
        var queryParam = {
          userId: this.userInfo.Id,
          creatorId: this.groupId || this.selectedUserId,
          markflag: true,
          isGroup: !!this.groupId,
          end: moment(endValue).format("YYYY-MM-DD HH:mm:ss")
        };

        D_UserMessage_GetPageHistoryDataList({
          PageIndex: 1,
          PageRows: 10,
          SortField: "CreateTime",
          SortType: "desc",
          Search: queryParam
        }).then(resJson => {
          this.messages.unshift(...(resJson.Data || []));
          this.loading = false;
        });
      }
    },
    getUnReadData() {
      if (this.selectedUserId) {
        this.loading = true;
        var queryParam = {
          userId: this.userInfo.Id,
          creatorId: this.groupId || this.selectedUserId,
          markflag: true,
          isGroup: !!this.groupId
        };
        D_UserMessage_GetHistoryDataList({
          Search: queryParam
        }).then(resJson => {
          this.messages = resJson.Data || [];
          this.loading = false;
        });
      }
    },
    handleCancel() {
      this.selectedUserId = null;
      this.visible = false;
    },
    getDataList() {
      this.loading = true;
      D_UserMessage_GetUserList().then(resJson => {
        this.loading = false;
        this.userdatas = resJson.Data;
        if (this.localdatas) {
          this.userdatas.forEach(item => {
            let tempdata = this.localdatas.find(d => d.UserId === item.UserId);
            if (tempdata) {
              item.LastDateTime = tempdata.LastDateTime;
              item.LastMessage = tempdata.LastMessage;
            }
          });
        }
      });
    },
    saveUserDatas() {
      localStorage.setItem("userdatas", JSON.stringify(this.userdatas));
    }
  },
  computed: {
    ...mapGetters(["userInfo"])
  },
  watch: {
    userdatas: {
      handler: "saveUserDatas",
      deep: true
    }
  }
};
</script>
